﻿using EventMgrLib;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using VisionRoc.Core;
using VisionRoc.Tool;

namespace VisionRoc_Measure
{
    public partial class FormDeletionModeTool : Form
    {
        public FormDeletionModeTool()
        {
            InitializeComponent();
        }

        // 静态实例字段
        private static FormDeletionModeTool _instance;

        // 全局访问点
        public static FormDeletionModeTool Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                {
                    _instance = new FormDeletionModeTool();
                }
                return _instance;
            }
        }

        private void FormDeletionModeTool_Load(object sender, EventArgs e)
        {
            EventMgr.Ins.GetEvent<ImageLogEvent>().Subscribe(LogHandle, log => log.SolutionName == "Main");
            txt_ResultImagePath.Text = Global.m_ImageAutoDelect.ResultImagePath;
            txt_ImagePath.Text = Global.m_ImageAutoDelect.ImagePath;
            txt_ResultSaveDay.Text = Global.m_ImageAutoDelect.ResultSaveDay.ToString();
            txt_SaveDay.Text = Global.m_ImageAutoDelect.ImageSaveDay.ToString();
            comboBox1.Text = Global.m_ImageAutoDelect.time.ToString();
            btn_Stop.Enabled = false;
            MyRefresh();
        }

        #region 添加日志信息

        private void LogHandle(ImageLogPayload obj)
        {
            AddLogListView(obj.Level, obj.LogMessage);
        }

        object log = new object();

        public void AddLogListView(int level, string Log)
        {
            lock (log)
            {
                Thread.Sleep(5);
                if (!this.lstInfo.InvokeRequired)
                {
                    if (Global.LogCount > 0)
                    {
                        if (lstInfo.Items.Count >= Global.LogCount)
                        {
                            lstInfo.Items.RemoveAt(lstInfo.Items.Count - 1);
                        }
                        ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString(" HH:mm:ss ff"), level);
                        lst.SubItems.Add(Log);
                        lstInfo.Items.Insert(0, lst);
                    }
                    else if (Global.LogCount < 0)
                    {
                        ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString("HH:mm:ss ff"), level);
                        lst.SubItems.Add(Log);
                        lstInfo.Items.Insert(0, lst);
                    }
                }
                else
                {
                    this.Invoke(new MethodInvoker(() =>
                    {
                        try
                        {
                            if (Global.LogCount > 0)
                            {
                                if (lstInfo.Items.Count >= Global.LogCount)
                                {
                                    lstInfo.Items.RemoveAt(lstInfo.Items.Count - 1);
                                }
                                ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString("HH:mm:ss ff"), level);
                                lst.SubItems.Add(Log);
                                lstInfo.Items.Insert(0, lst);
                            }
                            else if (Global.LogCount < 0)
                            {
                                ListViewItem lst = new ListViewItem("   " + DateTime.Now.ToString("HH:mm:ss ff"), level);
                                lst.SubItems.Add(Log);
                                lstInfo.Items.Insert(0, lst);
                            }
                        }
                        catch { }
                    }));
                }
            }
        }
        #endregion

        FixedTimeExecutor executor;
        private void btn_Start_Click(object sender, EventArgs e)
        {
            try
            {
                if (Directory.Exists(Global.m_ImageAutoDelect.ResultImagePath) && Directory.Exists(Global.m_ImageAutoDelect.ImagePath))
                {
                    btn_Start.Enabled = false;
                    btn_Stop.Enabled = true;
                    btn_Refresh.Enabled = false;
                    btn_Save.Enabled = false;
                    btn_ClearLog.Enabled = false;
                    txt_ResultSaveDay.Enabled = false;
                    txt_SaveDay.Enabled = false;


                    // 设置每天14:30执行
                    TimeSpan executionTime = new TimeSpan(Convert.ToInt32(comboBox1.Text), 00, 0);
                    //TimeSpan executionTime = new TimeSpan(20, 59, 0);
                    executor = new FixedTimeExecutor(executionTime, () =>
                   {
                       Global.AddAutoImageDelectEvent(LogLevel.OK,"【开始】图像自动删除线程开始执行");
                       Global.m_ImageAutoDelect.ResultImageFileMonitor(panel_ResultImageDelect);
                       Global.m_ImageAutoDelect.ImageFileMonitor(panel_ImageDelect);
                       Thread.Sleep(1000);
                       MyRefresh();
                       Global.AddAutoImageDelectEvent(LogLevel.OK, "【结束】图像自动删除线程执行结束");
                   });
                    executor.Start();
                    panel_ResultImageDelect.BackColor = Color.Chartreuse;
                    panel_ImageDelect.BackColor = Color.Chartreuse;
                    Global.AddAutoImageDelectEvent(LogLevel.OK, $"图像自动删除监控中···执行时间为{Global.m_ImageAutoDelect.time}时");
                }
                else
                {
                    Global.AddAutoImageDelectEvent(LogLevel.Warn, "图像路径不是本机路径监控失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                btn_Start.Enabled = true;
                btn_Stop.Enabled = false;
                btn_Refresh.Enabled = true;
                btn_Save.Enabled = true;
                btn_ClearLog.Enabled = true;
                txt_ResultSaveDay.Enabled = true;
                txt_SaveDay.Enabled = true;

            }

        }

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            try
            {
                executor.Stop();
                btn_Start.Enabled = true;
                btn_Stop.Enabled = false;
                btn_Refresh.Enabled = true;
                btn_Save.Enabled = true;
                btn_ClearLog.Enabled = true;
                txt_ResultSaveDay.Enabled = true;
                txt_SaveDay.Enabled = true;
                panel_ResultImageDelect.BackColor = Color.Red;
                panel_ImageDelect.BackColor = Color.Red;
                Global.AddAutoImageDelectEvent(LogLevel.OK, "停止图像监控");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void btn_ResultImagePath_Click(object sender, EventArgs e)
        {
            OpenFolderBrowser(txt_ResultImagePath, txt_CCD1ResuleFileNum, com_CCD1ResultFileInfo, "结果图像路径加载成功", out Global.m_ImageAutoDelect.ResultImagePath);
        }

        private void btn_ImagePath_Click(object sender, EventArgs e)
        {
            OpenFolderBrowser(txt_ImagePath, txt_CCD1FileNum, com_CCD1FileInfo, "原图图像路径加载成功", out Global.m_ImageAutoDelect.ImagePath);
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            MyRefresh();
            Global.AddAutoImageDelectEvent(LogLevel.OK, "刷新成功");
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                Global.m_ImageAutoDelect.ResultImagePath = txt_ResultImagePath.Text;
                Global.m_ImageAutoDelect.ImagePath = txt_ImagePath.Text;
                Global.m_ImageAutoDelect.ResultSaveDay = Convert.ToInt32(txt_ResultSaveDay.Text);
                Global.m_ImageAutoDelect.ImageSaveDay = Convert.ToInt32(txt_SaveDay.Text);
                Global.m_ImageAutoDelect.time = Convert.ToDouble(comboBox1.Text);
                Global.m_ImageAutoDelect.WriteParameter();
                panel_ResultImageDelect.BackColor = Color.Red;
                panel_ImageDelect.BackColor = Color.Red;
                MessageBox.Show("修改保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void btn_ClearLog_Click(object sender, EventArgs e)
        {
            lstInfo.Items.Clear();
        }

        public void OpenFolderBrowser(TextBox TextPath, TextBox TextFileNum, ComboBox ComFileInfo, string Message, out string ResultImagePath)
        {
            ResultImagePath = "";
            FolderBrowserDialog Save = new FolderBrowserDialog();
            Save.Description = "请选择文件夹路径";
            Save.ShowDialog();
            if (Save.SelectedPath != "")
            {
                ResultImagePath = TextPath.Text = Save.SelectedPath;
                DirectoryInfo d = new DirectoryInfo(ResultImagePath);
                FileSystemInfo[] fsinfos = d.GetFileSystemInfos();
                TextFileNum.Text = fsinfos.Length.ToString();
                ComFileInfo.Items.Clear();
                if (fsinfos.Length > 0)
                {
                    foreach (FileSystemInfo item in fsinfos)
                    {
                        if (item is DirectoryInfo)
                        {
                            TimeSpan t = DateTime.Now - Directory.GetCreationTime(item.FullName);
                            int DAY = t.Days;
                            ComFileInfo.Items.Add("文件名称:" + Path.GetFileName(item.FullName) + "。" + "文件已创建:" + DAY + "天");
                        }
                    }
                    ComFileInfo.Text = null;
                    ComFileInfo.SelectedIndex = 0;
                    Global.AddAutoImageDelectEvent(LogLevel.OK, Message);
                }
                else
                {
                    Global.AddAutoImageDelectEvent(LogLevel.Warn, $"该文件夹下没有发现子文件夹 :{fsinfos.Length.ToString()}");
                }

            }
        }

        public void MyRefresh()
        {
            try
            {
                Global.m_ImageAutoDelect.ReadParameter();
                if (Directory.Exists(Global.m_ImageAutoDelect.ResultImagePath))
                {
                    DirectoryInfo d = new DirectoryInfo(Global.m_ImageAutoDelect.ResultImagePath);
                    FileSystemInfo[] fsinfos = d.GetFileSystemInfos();
                    txt_CCD1ResuleFileNum.Text = fsinfos.Length.ToString();
                    if (fsinfos.Length != 0)
                    {
                        com_CCD1ResultFileInfo.Items.Clear();
                        foreach (FileSystemInfo item in fsinfos)
                        {
                            if (item is DirectoryInfo)
                            {
                                TimeSpan t = DateTime.Now - Directory.GetCreationTime(item.FullName);
                                int time = t.Days;
                                com_CCD1ResultFileInfo.Items.Add("文件名称:" + Path.GetFileName(item.FullName) + "。" + "文件已创建:" + time + "天");
                            }
                        }
                        com_CCD1ResultFileInfo.Text = "";
                        com_CCD1ResultFileInfo.SelectedIndex = 0;
                    }
                }
                else
                {
                    Global.AddAutoImageDelectEvent(LogLevel.Warn, Global.m_ImageAutoDelect.ResultImagePath + "   处理图像路径不存在");
                }

                if (Directory.Exists(Global.m_ImageAutoDelect.ImagePath))
                {
                    DirectoryInfo d = new DirectoryInfo(Global.m_ImageAutoDelect.ImagePath);
                    FileSystemInfo[] fsinfos = d.GetFileSystemInfos();
                    txt_CCD1FileNum.Text = fsinfos.Length.ToString();
                    if (fsinfos.Length != 0)
                    {
                        com_CCD1FileInfo.Items.Clear();
                        foreach (FileSystemInfo item in fsinfos)
                        {
                            if (item is DirectoryInfo)
                            {
                                TimeSpan t = DateTime.Now - Directory.GetCreationTime(item.FullName);
                                int time = t.Days;
                                com_CCD1FileInfo.Items.Add("文件名称:" + Path.GetFileName(item.FullName) + "。" + "文件已创建:" + time + "天");
                            }
                        }
                        com_CCD1FileInfo.Text = "";
                        com_CCD1FileInfo.SelectedIndex = 0;
                    }
                }
                else
                {
                    Global.AddAutoImageDelectEvent(LogLevel.Warn, Global.m_ImageAutoDelect.ResultImagePath + "   原图图像路径不存在");
                }
                //Global.AddAutoImageDelectEvent(LogLevel.Info, "刷新成功！");
            }
            catch (Exception ex)
            {
                Global.AddAutoImageDelectEvent(LogLevel.Warn, "刷新异常！！！  已写入文本");
                TxtAPI.WriteLogTxt("图像自动删除刷新异常 ：" + ex.ToString());
            }
        }

      
    }


    public class FixedTimeExecutor
    {
        private readonly TimeSpan _executionTime;
        private readonly Action _action;
        private System.Threading.Timer _timer;
        private bool _isRunning = false;
        private readonly object _lockObject = new object();

        public FixedTimeExecutor(TimeSpan executionTime, Action action)
        {
            _executionTime = executionTime;
            _action = action;
        }

        public void Start()
        {
            lock (_lockObject)
            {
                if (_isRunning)
                    return;

                _isRunning = true;
                ScheduleNextExecution();
            }
        }

        public void Stop()
        {
            lock (_lockObject)
            {
                if (!_isRunning)
                    return;

                _isRunning = false;
                _timer?.Dispose();
                _timer = null;
            }
        }

        private void ScheduleNextExecution()
        {
            DateTime now = DateTime.Now;
            DateTime scheduledTime = now.Date.Add(_executionTime);

            // 如果今天的执行时间已过，则安排到明天
            if (scheduledTime <= now)
                scheduledTime = scheduledTime.AddDays(1);

            TimeSpan delay = scheduledTime - now;
            _timer = new System.Threading.Timer(ExecuteAction, null, delay, Timeout.InfiniteTimeSpan);
        }

        private void ExecuteAction(object state)
        {
            try
            {
                // 使用 Task.Run 在线程池线程上执行操作
                Task.Run(() => _action());
            }
            catch (Exception ex)
            {
                Console.WriteLine($"执行操作时发生错误: {ex}");
            }
            finally
            {
                // 安排下一次执行
                if (_isRunning)
                {
                    lock (_lockObject)
                    {
                        if (_isRunning)
                        {
                            ScheduleNextExecution();
                        }
                    }
                }
            }
        }

    }

}
